﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Globalization;
using System.Text;
using System.Linq;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.Configuration;
using System.Web;
using System.Runtime.InteropServices;
using System.IO;
using System.Web.UI.WebControls;
using System.Security.Cryptography;

namespace CMS
{
    public static class CMD 
    {
        public static int Insert = 1;
        public static int Update = 2;
        public static int Delete = 3;
        public static int LastLogin = 4;
        public static int View = 0;
    }

    public class ReplaceBoolean
    {
        string replace = "";
        public string Replace(Boolean? input)
        {
            if (input.HasValue)
            {
                if (input.Value == true)
                {
                    replace = "Yes";
                }
                else
                {
                    replace = "No";
                }
            }

            return replace;
        }
    }

    public static class PayDay
    {
        private static DateTime? HRS_PAYDAY;

        public static Boolean CheckPayDay()
        {
            List<CMS.Hours> Hours = CMS.Hours.GetHours(CMS.Functions.AdministrationID, null, CMS.Functions.UserID, null, null, null, null, null, null);
            if (Hours != null)
            {
                foreach (var hrs in Hours)
                {
                    if (hrs.HRS_PAYDAY.ToString() != null)
                    {
                        HRS_PAYDAY = hrs.HRS_PAYDAY;
                        return DateTime.Now.Date.ToShortDateString() == HRS_PAYDAY.Value.Date.ToShortDateString();
                    }
                    else
                    {
                        return false;
                    }
                }
            }
            else
            {
                return false;
            }
            return false;
        }
    }

    public static class Rights
    {
        public static Boolean USR;
        public static Boolean PAG;
        public static Boolean UPL;
        public static Boolean HRS;

        public static void GetPermission(Int64? ADM_ID,Int64? USR_ID)
        {
            if (ADM_ID.HasValue)
            {
                // Procedure call look if they have permissions !
                var GetPerms = CMS.Permission.GetPermission(ADM_ID, null, USR_ID, null, null, null,null, null).SingleOrDefault();
                if (GetPerms != null)
                {
                    PAG = GetPerms.PAG;
                    USR = GetPerms.USR;
                    UPL = GetPerms.UPL;
                    HRS = GetPerms.HRS;
                }
            }
        }

        public static StoredProcedureValues InsertPermission(int Action, Int64? ADM_ID, Int64? PERM_ID, Int64? USR_ID, Boolean UPL, Boolean USR, Boolean PAG, Boolean HRS, String PERM_NAME = "")
        {
            if (ADM_ID.HasValue && USR_ID.HasValue)
            {
                // Procedure call insert permissions !
                return StoredProcedureValues.SP_Permissions(Action, ADM_ID, PERM_ID, USR_ID, UPL, USR, PAG,HRS, PERM_NAME);
            }
            else
            {
                return StoredProcedureValues.Empty();
            }
        }

    }

    public struct Functions
    {
        public static StoredProcedureValues UserLastLogin(Int64 Action, Int64? UserID, Int64? ADM_ID, string IsMasterUserError = "")
        {
            if (Action == CMD.LastLogin && UserID > 0 && ADM_ID > 0)
            {
                return StoredProcedureValues.SP_User(CMD.LastLogin, UserID, ADM_ID, null, null, null, null, DateTime.Now.ToLongDateString() +" "+ DateTime.Now.ToShortTimeString(),null);
            }
            return StoredProcedureValues.Empty();
        }

        public static string IsError = null;
        public static Boolean VerifyMasterUser;
        public static Boolean IsMasterUser(string IsMasterUserError = "", string ForbiddenPage = "")
        {
            var aUser = Users.GetUsers(UserID, null, null, null, AdministrationID, null, null, null).FirstOrDefault();
           
            if (aUser != null && aUser.USR_ACTIVE.Value == true)
            {
                VerifyMasterUser = aUser.USR_MASTERUSER.Value;
                return aUser.USR_MASTERUSER.Value;
            }
            
            if (aUser != null)
            {
                IsError = aUser.USR_MASTERUSER.Value == false ? ConfirmPopup(IsMasterUserError, ForbiddenPage, System.Drawing.KnownColor.Red) : null;
            }

            VerifyMasterUser = false;
            return false;
        }

        /// <summary>
        /// This class generates and compares hashes using MD5, SHA1, SHA256, SHA384, 
        /// and SHA512 hashing algorithms. Before computing a hash, it appends a
        /// randomly generated salt to the plain text, and stores this salt appended
        /// to the result. To verify another plain text value against the given hash,
        /// this class will retrieve the salt value from the hash string and use it
        /// when computing a new hash of the plain text. Appending a salt value to
        /// the hash may not be the most efficient approach, so when using hashes in
        /// a real-life application, you may choose to store them separately. You may
        /// also opt to keep results as byte arrays instead of converting them into
        /// base64-encoded strings.
        /// </summary>
        public class Hash
        {
            /// <summary>
            /// Generates a hash for the given plain text value and returns a
            /// base64-encoded result. Before the hash is computed, a random salt
            /// is generated and appended to the plain text. This salt is stored at
            /// the end of the hash value, so it can be used later for hash
            /// verification.
            /// </summary>
            /// <param name="plainText">
            /// Plaintext value to be hashed. The function does not check whether
            /// this parameter is null.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1",
            /// "SHA256", "SHA384", and "SHA512" (if any other value is specified
            /// MD5 hashing algorithm will be used). This value is case-insensitive.
            /// </param>
            /// <param name="saltBytes">
            /// Salt bytes. This parameter can be null, in which case a random salt
            /// value will be generated.
            /// </param>
            /// <returns>
            /// Hash value formatted as a base64-encoded string.
            /// </returns>
            public static string ComputeHash(string plainText,
                                             string hashAlgorithm,
                                             byte[] saltBytes)
            {
                // If salt is not specified, generate it on the fly.
                if (saltBytes == null)
                {
                    // Define min and max salt sizes.
                    int minSaltSize = 4;
                    int maxSaltSize = 8;

                    // Generate a random number for the size of the salt.
                    Random random = new Random();
                    int saltSize = random.Next(minSaltSize, maxSaltSize);

                    // Allocate a byte array, which will hold the salt.
                    saltBytes = new byte[saltSize];

                    // Initialize a random number generator.
                    RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();

                    // Fill the salt with cryptographically strong byte values.
                    rng.GetNonZeroBytes(saltBytes);
                }

                // Convert plain text into a byte array.
                byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);

                // Allocate array, which will hold plain text and salt.
                byte[] plainTextWithSaltBytes =
                        new byte[plainTextBytes.Length + saltBytes.Length];

                // Copy plain text bytes into resulting array.
                for (int i = 0; i < plainTextBytes.Length; i++)
                    plainTextWithSaltBytes[i] = plainTextBytes[i];

                // Append salt bytes to the resulting array.
                for (int i = 0; i < saltBytes.Length; i++)
                    plainTextWithSaltBytes[plainTextBytes.Length + i] = saltBytes[i];

                // Because we support multiple hashing algorithms, we must define
                // hash object as a common (abstract) base class. We will specify the
                // actual hashing algorithm class later during object creation.
                HashAlgorithm hash;

                // Make sure hashing algorithm name is specified.
                if (hashAlgorithm == null)
                    hashAlgorithm = "";

                // Initialize appropriate hashing algorithm class.
                switch (hashAlgorithm.ToUpper())
                {
                    case "SHA1":
                        hash = new SHA1Managed();
                        break;

                    case "SHA256":
                        hash = new SHA256Managed();
                        break;

                    case "SHA384":
                        hash = new SHA384Managed();
                        break;

                    case "SHA512":
                        hash = new SHA512Managed();
                        break;

                    default:
                        hash = new MD5CryptoServiceProvider();
                        break;
                }

                // Compute hash value of our plain text with appended salt.
                byte[] hashBytes = hash.ComputeHash(plainTextWithSaltBytes);

                // Create array which will hold hash and original salt bytes.
                byte[] hashWithSaltBytes = new byte[hashBytes.Length +
                                                    saltBytes.Length];

                // Copy hash bytes into resulting array.
                for (int i = 0; i < hashBytes.Length; i++)
                    hashWithSaltBytes[i] = hashBytes[i];

                // Append salt bytes to the result.
                for (int i = 0; i < saltBytes.Length; i++)
                    hashWithSaltBytes[hashBytes.Length + i] = saltBytes[i];

                // Convert result into a base64-encoded string.
                string hashValue = Convert.ToBase64String(hashWithSaltBytes);

                // Return the result.
                return hashValue;
            }

            /// <summary>
            /// Compares a hash of the specified plain text value to a given hash
            /// value. Plain text is hashed with the same salt value as the original
            /// hash.
            /// </summary>
            /// <param name="plainText">
            /// Plain text to be verified against the specified hash. The function
            /// does not check whether this parameter is null.
            /// </param>
            /// <param name="hashAlgorithm">
            /// Name of the hash algorithm. Allowed values are: "MD5", "SHA1", 
            /// "SHA256", "SHA384", and "SHA512" (if any other value is specified,
            /// MD5 hashing algorithm will be used). This value is case-insensitive.
            /// </param>
            /// <param name="hashValue">
            /// Base64-encoded hash value produced by ComputeHash function. This value
            /// includes the original salt appended to it.
            /// </param>
            /// <returns>
            /// If computed hash mathes the specified hash the function the return
            /// value is true; otherwise, the function returns false.
            /// </returns>
            public static bool VerifyHash(string plainText,
                                          string hashAlgorithm,
                                          string hashValue)
            {
                // Convert base64-encoded hash value into a byte array.
                byte[] hashWithSaltBytes = Convert.FromBase64String(hashValue);

                // We must know size of hash (without salt).
                int hashSizeInBits, hashSizeInBytes;

                // Make sure that hashing algorithm name is specified.
                if (hashAlgorithm == null)
                    hashAlgorithm = "";

                // Size of hash is based on the specified algorithm.
                switch (hashAlgorithm.ToUpper())
                {
                    case "SHA1":
                        hashSizeInBits = 160;
                        break;

                    case "SHA256":
                        hashSizeInBits = 256;
                        break;

                    case "SHA384":
                        hashSizeInBits = 384;
                        break;

                    case "SHA512":
                        hashSizeInBits = 512;
                        break;

                    default: // Must be MD5
                        hashSizeInBits = 128;
                        break;
                }

                // Convert size of hash from bits to bytes.
                hashSizeInBytes = hashSizeInBits / 8;

                // Make sure that the specified hash value is long enough.
                if (hashWithSaltBytes.Length < hashSizeInBytes)
                    return false;

                // Allocate array to hold original salt bytes retrieved from hash.
                byte[] saltBytes = new byte[hashWithSaltBytes.Length -
                                            hashSizeInBytes];

                // Copy salt from the end of the hash to the new array.
                for (int i = 0; i < saltBytes.Length; i++)
                    saltBytes[i] = hashWithSaltBytes[hashSizeInBytes + i];

                // Compute a new hash string.
                string expectedHashString =
                            ComputeHash(plainText, hashAlgorithm, saltBytes);

                // If the computed hash matches the specified hash,
                // the plain text value must be correct.
                return (hashValue == expectedHashString);
            }
        }


        private static string UserName;
        public static string Username
        {
            get
            {
                return UserName;
            }
            set
            {
                UserName = value;
            }
        }


        private static string AdministrationName;
        public static string Administrationname
        {
            get
            {
                return AdministrationName;
            }
            set
            {
                AdministrationName = value;
            }
        }

        private static Int64? _AdministrationID;
        public static Int64? AdministrationID
        {
            get
            {
                return _AdministrationID;
            }
            set
            {
                _AdministrationID = value;
            }
        }

        private static Int64? _UserID;
        public static Int64? UserID
        {
            get
            {
                return _UserID;
            }
            set
            {
                _UserID = value;
            }

        }



        public static void AuthorizeLogin(Action<string> redirect)
        {
            if (ReadCookie(Username))
            {
                redirect("/Login.aspx?ClearSession=1");
            }
        }

        public static void MakeLoginCookie(String UserID)
        {
            //Create a new cookie, passing the name into the constructor
            HttpCookie cookie = new HttpCookie(UserID);

            //Set the cookies value
            cookie.Value = UserName;

            //Set the cookie to expire in 30 minutes
            DateTime dtNow = DateTime.Now;
            TimeSpan tsMinute = new TimeSpan(0, 0, 30, 0);
            cookie.Expires = dtNow + tsMinute;

            //Add the cookie
            HttpContext.Current.Response.Cookies.Add(cookie);
        }

        public static Boolean ReadCookie(String UserID)
        {
            String CookieName;
            HttpCookie cookie;
            //Get the cookie name the user entered
            if (HttpContext.Current.Request.QueryString[UserID] != null)
            {
                CookieName = HttpContext.Current.Request.QueryString[UserID].ToString();
                //Grab the cookie
                cookie = HttpContext.Current.Request.Cookies[CookieName];

                //Check to make sure the cookie exists
                if (cookie == null)
                {
                    return false;
                }
                else
                {
                    //Write the cookie value
                    MakeLoginCookie(UserID);
                    //String strCookieValue = cookie.Value.ToString();
                    return true;
                }
            }
            else
            {
                return false;
            }
        }




        /// <summary>
        /// This method is used for password policy the user needs to be put in a safer password
        /// </summary>
        /// <param name="MinLenght">Minium lenght of a password before accepted.</param>
        /// <param name="Input">The password given by the user.</param>
        /// <param name="ErrorMinLength">Error message for Minlenght if not fits (Optional).</param>       
        /// <returns>The password when it fits the MinLenght.</returns>
        public static string PasswordPolicy(Int64 MinLenght, string Input, string ErrorMinLenght = "", string ExtraParamsErrorMinLenght = null, System.Drawing.KnownColor Color = System.Drawing.KnownColor.Red)
        {
            string sResult = "";
            if (Input.Length >= MinLenght)
            {
                sResult = Input;
            }
            else
            {
                IsError = NormalPopup("<span style=\"font-scolor:" + Color.ToString() + "\">" + ErrorMinLenght + "</span>", System.Drawing.KnownColor.Red, ExtraParamsErrorMinLenght);
            }

            return sResult;
        }

        /// <summary>
        ///  Function to show Normal Popup window 
        /// </summary>
        /// <param name="Message">Message that is displayed in the popup</param>
        /// <param name="ExtraParams">For extra Javascript functions like red borders or something its an optional param</param>
        /// <returns>Returns The javascript for Apprise Popup</returns>
        public static string NormalPopup(String Message, System.Drawing.KnownColor Color = System.Drawing.KnownColor.Black, String ExtraParams = "")
        {
            if(!String.IsNullOrEmpty(Message))
            {
                return "apprise('" + "<span style=\"color:"+ Color.ToString() +"\">" + Message.Replace("'", "") + "</span>" + "');" + ExtraParams + "";
            }
            return String.Empty;
        }



        public static string PopupPayDay(String Message, System.Drawing.KnownColor Color = System.Drawing.KnownColor.Black, String ExtraParams = "", Boolean? ResetPayDay = false)
        {
            if (!String.IsNullOrEmpty(Message))
            {
                return "apprise('" + "<span style=\"color:" + Color.ToString() + "\">" + Message.Replace("'", "") + "</span>" + "');" + ExtraParams + "";
            }
            return String.Empty;
        }

        /// <summary>
        ///  Function to show Confirm Popup window 
        /// </summary>
        /// <param name="Message">Message that is displayed in the popup</param>
        /// <param name="ConfirmUrl">Redirects to Given url</param>
        /// <param name="ExtraParams">For extra Javascript functions like red borders or something its an optional param</param>
        /// <returns>Returns The javascript for Apprise ConfirmPopup</returns>
        public static string ConfirmPopup(String Message, String ConfirmUrl, System.Drawing.KnownColor Color = System.Drawing.KnownColor.Black, String ExtraParams = "")
        {
            if (!String.IsNullOrEmpty(Message) && !String.IsNullOrEmpty(ConfirmUrl))
            {
                return "apprise('"+ "<span id=\"ConfirmPopup\" style=\"color:"+ Color.ToString() +"\">" + Message.Replace("'", "") + "</span>" +"', {'animate':true}, function(r) {if(r) {window.location='"+ ConfirmUrl +"'; } });"+ ExtraParams +"";
            }
            return String.Empty;
        }

        /// <summary>
        /// Returns a MailAddress or null if no valid email address
        /// </summary>
        public static MailAddress GetEmailAddress(String email)
        {
            string regexMail = ConfigurationManager.AppSettings["RegexMail"]; //@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*";
            if (string.IsNullOrEmpty(email))
            { return null; }

            if (Regex.IsMatch(email, regexMail))
            { return new MailAddress(email); }

            return null;
        }

        /// <summary>
        /// Tries to convert an object to a boolean, returns null on failure.
        /// </summary>
        public static bool? NullableBoolean(object Input)
        {
            return NullableBoolean(Input, null);
        }
        /// <summary>
        /// Tries to convert an object to a boolean, returns null on failure.
        /// </summary>
        public static bool? NullableBoolean(object Input, bool? returnIfNull)
        {
            if (Input == null || Input == DBNull.Value) return returnIfNull;
            bool tmpBoolean;
            if (Boolean.TryParse(Input.ToString(), out tmpBoolean)) { returnIfNull = tmpBoolean; }
            return returnIfNull;
        }




        /// <summary>
        /// Tries to convert an object to a decimal, returns null on failure.
        /// </summary>
        public static decimal? NullableDecimal(object Input)
        {
            return NullableDecimal(Input, null);
        }

        /// <summary>
        /// Tries to convert an object to a decimal, returns null on failure.
        /// </summary>
        public static decimal? NullableDecimal(object Input, decimal? returnIfNull)
        {
            if (Input == null || Input == DBNull.Value) return returnIfNull;
            decimal tmpDecimal;
            if (Decimal.TryParse(Input.ToString(), out tmpDecimal)) { returnIfNull = tmpDecimal; }
            return returnIfNull;
        }

        /// <summary>
        /// Tries to convert an object to a guid, returns null on failure.
        /// </summary>
        public static Guid? NullableGuid(object Input)
        {
            if (Input == null) return null;
            Guid? OutGuid;
            try
            { OutGuid = new Guid(Input.ToString()); }
            catch
            { OutGuid = null; }

            return OutGuid;
        }

        /// <summary>
        /// Tries to convert an object to an integer, returns null on failure.
        /// </summary>
        public static int? NullableInt(object Input)
        {
            return NullableInt(Input, null);
        }
        /// <summary>
        /// Tries to convert an object to an integer, returns null on failure.
        /// </summary>
        public static int? NullableInt(object Input, int? returnIfNull)
        {
            if (Input == null || Input == DBNull.Value) return returnIfNull;
            int tmpInt;
            if (Int32.TryParse(Input.ToString(), out tmpInt)) { returnIfNull = tmpInt; }
            return returnIfNull;
        }


        /// <summary>
        /// Tries to convert an object to an integer, returns null on failure.
        /// </summary>
        public static Int64? NullableLong(object Input)
        {
            return NullableLong(Input, null);
        }
        /// <summary>
        /// Tries to convert an object to an integer, returns null on failure.
        /// </summary>
        public static Int64? NullableLong(object Input, Int64? returnIfNull)
        {
            if (Input == null || Input == DBNull.Value) return returnIfNull;
            Int64 tmpInt;
            if (Int64.TryParse(Input.ToString(), out tmpInt)) { returnIfNull = tmpInt; }
            return returnIfNull;
        }


        /// <summary>
        /// Tries to convert an object to a datetime, returns null on failure.
        /// </summary>
        public static DateTime? NullableDatetime(object Input)
        {
            return NullableDatetime(Input, null);
        }
        /// <summary>
        /// Tries to convert an object to a datetime, returns null on failure.
        /// </summary>
        public static DateTime? NullableDatetime(object Input, DateTime? returnIfNull)
        {
            if (Input == null || Input == DBNull.Value) return returnIfNull;
            DateTime tmpDate;
            if (DateTime.TryParse(Input.ToString(), out tmpDate)) { returnIfNull = tmpDate; }
            return returnIfNull;
        }


        /// <summary>
        /// Sets a given datagrid's First, Previous, Next and Last arrow buttons
        /// </summary>
        public static void SetDataGridButtons(DataGrid Grid, ImageButton ButtonFirst, ImageButton ButtonPrevious, ImageButton ButtonNext, ImageButton ButtonLast)
        {
            ButtonFirst.CommandArgument = "0";
            ButtonPrevious.CommandArgument = "prev";
            ButtonNext.CommandArgument = "next";
            ButtonLast.CommandArgument = "last";

            if (Grid.CurrentPageIndex > 0)
            {
                ButtonFirst.Enabled = true;
                ButtonFirst.ImageUrl = "images/DataGridNavigationFirstOn.gif";
                ButtonPrevious.Enabled = true;
                ButtonPrevious.ImageUrl = "images/DataGridNavigationPreviousOn.gif";
            }
            else
            {
                ButtonFirst.Enabled = false;
                ButtonFirst.ImageUrl = "images/DataGridNavigationFirstOff.gif";
                ButtonPrevious.Enabled = false;
                ButtonPrevious.ImageUrl = "images/DataGridNavigationPreviousOff.gif";
            }

            if (Grid.CurrentPageIndex >= Grid.PageCount - 1)
            {
                ButtonLast.Enabled = false;
                ButtonLast.ImageUrl = "images/DataGridNavigationLastOff.gif";
                ButtonNext.Enabled = false;
                ButtonNext.ImageUrl = "images/DataGridNavigationNextOff.gif";
            }
            else
            {
                ButtonLast.Enabled = true;
                ButtonLast.ImageUrl = "images/DataGridNavigationLastOn.gif";
                ButtonNext.Enabled = true;
                ButtonNext.ImageUrl = "images/DataGridNavigationNextOn.gif";
            }
        }

        /// <summary>
        /// This method is used to convert the DataTable into string XML format.
        /// </summary>
        /// <param name="dtBuildSQL">DataTable to be converted.</param>
        /// <returns>(string) XML form of the DataTable.</returns>
        public static string DataTableToXML(DataTable dtBuildSQL)
        {
            DataSet dsBuildSQL = new DataSet();
            StringBuilder sbSQL;
            StringWriter swSQL;
            string XMLformat;

            sbSQL = new StringBuilder();
            swSQL = new StringWriter(sbSQL);
            dsBuildSQL.Merge(dtBuildSQL, true, MissingSchemaAction.AddWithKey);
            dsBuildSQL.Tables[0].TableName = "Table";
            foreach (DataColumn col in dsBuildSQL.Tables[0].Columns)
            {
                col.ColumnMapping = MappingType.Attribute;
            }
            dsBuildSQL.WriteXml(swSQL, XmlWriteMode.WriteSchema);
            XMLformat = sbSQL.ToString();
            return XMLformat;
        }

        public class VerifyLogin
        {
            public static Boolean _Valid;
            public static Boolean Valid
            {
                get { return _Valid; }
                set { _Valid = value; }
            }


            public static Boolean Verify(String UserName, string Password, Int64? ADM_ID, string ADM_NAME, string InvalidError = "", string ExtraParams = "")
            {
                var aUser = Users.GetUsers(null, UserName, null, null, ADM_ID, null, null,null).FirstOrDefault();
                if (aUser != null)
                {
                    if (!aUser.USR_ACTIVE.Value == false)
                    {
                        Valid = Hash.VerifyHash(Password, "MD5", aUser.USR_PASSWORD);
                        IsError = NormalPopup("<span style=\"font-weight:bold;\">"+InvalidError+"</span>", System.Drawing.KnownColor.Black, ExtraParams);
                    }
                    else
                    {
                        IsError = NormalPopup("<span style=\"color:Black;\">Username:</span> <span style=\"color:Red;font-weight:bold;\">" + UserName + "</span><span style=\"color:Black;\"> is not active !</span>", System.Drawing.KnownColor.Red, ExtraParams);
                    }

                    return Valid;
                }
                else if (aUser != null && ADM_ID != aUser.ADM_ID)
                {
                    IsError = NormalPopup("<span style=\"color:Black;\">Administration: </span> <span style=\"color:Red;font-weight:bold;\">" + ADM_NAME + "</span><span style=\"color:Black;\"> is not active on user : </span> <span style=\"color:Red;font-weight:bold;\">" + UserName + "</span> <span style=\"color:Black;\">!</span>", System.Drawing.KnownColor.Red, ExtraParams);
                }
                else
                if (aUser == null)
                {
                    IsError = NormalPopup("<span style=\"color:Black;\"> Username: </span> <span style=\"color:Red;font-weight:bold;\">" + UserName + " </span><span style=\"color:Black;\"> doesn't exists !</span>", System.Drawing.KnownColor.Red, ExtraParams);
                }

                return aUser != null;
            }
        }

        public string LogOut()
        {
           HttpContext.Current.Session.Abandon();
           HttpContext.Current.Request.Cookies.Remove(UserID.ToString());
           VerifyLogin.Valid = false;
           return "window.location='Login.aspx?ClearSession=1'";
        }
   
        /// <summary>
        ///  To Excute an redirection
        /// </summary>
        /// <param name="Execute">To execute the funtion</param>
        /// <param name="UrlToRedirect">To redirect just fill in the Url where you want to go When empty it would use Login.aspx as default</param>
        /// <returns></returns>
        /// 

        private static string Redirect(bool Execute, string UrlToRedirect)
        {
            if (Execute)
            {
                if (!String.IsNullOrEmpty(UrlToRedirect))
                {
                    System.Web.HttpContext.Current.Response.Redirect(UrlToRedirect);
                }
                else
                {
                    System.Web.HttpContext.Current.Response.Redirect("Login.aspx");
                }
            }
            return null;
        }
    }

    public struct StoredProcedureValues
    {
        public int Error;
        public int Identity;
        public string Message;
        public string Constraint
        {
            get
            {
                string OutString = string.Empty;
                Match ConstraintMatch;

                switch (Error)
                {
                    case 515:
                        ConstraintMatch = Regex.Match(Message, "Cannot insert the value NULL into column '(.*?)'");
                        OutString = ConstraintMatch.Groups[1].ToString();
                        break;
                    case 2627:
                        ConstraintMatch = Regex.Match(Message, "Violation of UNIQUE KEY constraint '(.*?)'");
                        OutString = ConstraintMatch.Groups[1].ToString();
                        break;
                }

                return OutString;
            }
        }

        public static StoredProcedureValues Empty()
        {
            StoredProcedureValues Empty = new StoredProcedureValues();
            return Empty;
        }

        public static StoredProcedureValues SP_Administration(int Action, long? AdministrationID, string AdministrationCode, string AdministrationName, Boolean? Active, string Admcomments, DateTime? AdmDate)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Administration", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.Int).Value = Action;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@ADM_CODE", SqlDbType.VarChar).Value = AdministrationCode;
                    Command.Parameters.Add("@ADM_NAME", SqlDbType.VarChar).Value = AdministrationName;
                    Command.Parameters.Add("@ADM_ACTIVE", SqlDbType.Bit).Value = Active;
                    Command.Parameters.Add("@ADM_COMMENTS", SqlDbType.VarChar).Value = Admcomments;
                    Command.Parameters.Add("@ADM_DATE", SqlDbType.DateTime).Value = AdmDate;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }


        public static DataTable VW_Administration(Int64? AdministrationID, string AdministrationCode, string AdministrationName, Boolean? Active, string Admcomments, DateTime? AdmDate)
        {
            DataTable OutTable = new DataTable("Administrations");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Administration", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@ADM_CODE", SqlDbType.VarChar).Value = AdministrationCode;
                    Command.Parameters.Add("@ADM_NAME", SqlDbType.VarChar).Value = AdministrationName;
                    Command.Parameters.Add("@ADM_ACTIVE", SqlDbType.Bit).Value = Active;
                    Command.Parameters.Add("@ADM_COMMENTS", SqlDbType.VarChar).Value = Admcomments;
                    Command.Parameters.Add("@ADM_DATE", SqlDbType.DateTime).Value = AdmDate;
          
                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                }
            }

            return OutTable;
        }

        public static DataTable VW_Pages(long? AdministrationID, long? PAG_ID, String Pag_title, String PAG_CONTENT, String PAG_KEYWORDS, String PAG_METATAGS, Boolean? PAG_VISIBLE)
        {
            DataTable OutTable = new DataTable("SP_VW_Pages");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ConnectionString))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Pages", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@PAG_ID", SqlDbType.BigInt).Value = PAG_ID;
                    Command.Parameters.Add("@PAG_TITLE", SqlDbType.VarChar).Value = Pag_title;
                    Command.Parameters.Add("@PAG_CONTENT", SqlDbType.VarChar).Value = PAG_CONTENT;
                    Command.Parameters.Add("@PAG_KEYWORDS", SqlDbType.VarChar).Value = PAG_KEYWORDS;
                    Command.Parameters.Add("@PAG_METATAGS", SqlDbType.VarChar).Value = PAG_METATAGS;
                    Command.Parameters.Add("@PAG_VISIBLE", SqlDbType.Bit).Value = PAG_VISIBLE;

                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                    Connection.Close();
                }
            }

            return OutTable;
        }


        public static StoredProcedureValues SP_Pages(int Action,long? PAG_ID, long? AdministrationID, String Pag_title, String PAG_CONTENT, String PAG_KEYWORDS, String PAG_METATAGS, Boolean? PAG_VISIBLE)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Page", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.Int).Value = Action;
                    Command.Parameters.Add("@PAG_ID", SqlDbType.BigInt).Value = PAG_ID;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@PAG_TITLE", SqlDbType.VarChar).Value = Pag_title;
                    Command.Parameters.Add("@PAG_CONTENT", SqlDbType.VarChar).Value = PAG_CONTENT;
                    Command.Parameters.Add("@PAG_KEYWORDS", SqlDbType.VarChar).Value = PAG_KEYWORDS;
                    Command.Parameters.Add("@PAG_METATAGS", SqlDbType.VarChar).Value = PAG_METATAGS;
                    Command.Parameters.Add("@PAG_VISIBLE", SqlDbType.Bit).Value = PAG_VISIBLE;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }


        public static StoredProcedureValues SP_User(int Action, long? ID, long? AdministrationID, String Name, String Password, String Email, Boolean? Active, string LastLogin, Boolean? UserMaster)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Users", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.Int).Value = Action;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = ID;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@USR_NAME", SqlDbType.VarChar).Value = Name;
                    Command.Parameters.Add("@USR_PASSWORD", SqlDbType.VarChar).Value = Password;
                    Command.Parameters.Add("@USR_EMAIL", SqlDbType.VarChar).Value = Email;
                    Command.Parameters.Add("@USR_ACTIVE", SqlDbType.Bit).Value = Active;
                    Command.Parameters.Add("@USR_LASTLOGIN", SqlDbType.VarChar).Value = LastLogin;
                    Command.Parameters.Add("@USR_MASTERUSER", SqlDbType.Bit).Value = UserMaster;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }

        public static DataTable VW_Users(Int64? UserID, string UserName, string Password,string Email, long? AdministrationID, Boolean? Active, string LastLogin, Boolean? UserMaster)
        {
            DataTable OutTable = new DataTable("Users");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Users", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = UserID;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = AdministrationID;
                    Command.Parameters.Add("@USR_NAME", SqlDbType.VarChar).Value = UserName;
                    Command.Parameters.Add("@USR_PASSWORD", SqlDbType.VarChar).Value = Password;
                    Command.Parameters.Add("@USR_EMAIL", SqlDbType.VarChar).Value = Email;
                    Command.Parameters.Add("@USR_ACTIVE", SqlDbType.Bit).Value = Active;
                    Command.Parameters.Add("@USR_LASTLOGIN", SqlDbType.VarChar).Value = LastLogin;
                    Command.Parameters.Add("@USR_MASTERUSER", SqlDbType.Bit).Value = UserMaster;

                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                }
            }

            return OutTable;
        }

        public static StoredProcedureValues SP_Upload(int Action, Int64? ADM_ID, Int64? UPL_ID, Int64? USR_ID, String UPL_NAME, String UPL_GUID, String UPL_COMMENTS)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();
        
            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Upload", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.BigInt).Value = Action;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@UPL_ID", SqlDbType.BigInt).Value = UPL_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;

                    Command.Parameters.Add("@UPL_NAME", SqlDbType.VarChar).Value = UPL_NAME;
                    Command.Parameters.Add("@UPL_GUID", SqlDbType.VarChar).Value = UPL_GUID;
                    Command.Parameters.Add("@UPL_COMMENTS", SqlDbType.VarChar).Value = UPL_COMMENTS;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }

        public static DataTable VW_Upload(Int64? ADM_ID, Int64? UPL_ID, Int64? USR_ID, String UPL_NAME, String UPL_GUID, String UPL_COMMENTS)
        {
            DataTable OutTable = new DataTable("Upload");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Upload", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@UPL_ID", SqlDbType.BigInt).Value = UPL_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;

                    Command.Parameters.Add("@UPL_NAME", SqlDbType.VarChar).Value = UPL_NAME;
                    Command.Parameters.Add("@UPL_GUID", SqlDbType.VarChar).Value = UPL_GUID;
                    Command.Parameters.Add("@UPL_COMMENTS", SqlDbType.VarChar).Value = UPL_COMMENTS;

                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                }
            }

            return OutTable;
        }

        public static StoredProcedureValues SP_Permissions(int Action, Int64? ADM_ID, Int64? PERM_ID, Int64? USR_ID, Boolean? UPL, Boolean? USR, Boolean? PAG, Boolean? HRS, String PERM_NAME)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Permissions", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.Int).Value = Action;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@PERM_ID", SqlDbType.BigInt).Value = PERM_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;
                    Command.Parameters.Add("@UPL", SqlDbType.Bit).Value = UPL;
                    Command.Parameters.Add("@USR", SqlDbType.Bit).Value = USR;
                    Command.Parameters.Add("@PAG", SqlDbType.Bit).Value = PAG;
                    Command.Parameters.Add("@HRS", SqlDbType.Bit).Value = HRS;
                    Command.Parameters.Add("@PERM_NAME", SqlDbType.VarChar).Value = PERM_NAME;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }

        public static DataTable VW_Permissions(Int64? ADM_ID, Int64? PERM_ID, Int64? USR_ID, Boolean? UPL, Boolean? USR, Boolean? PAG, Boolean? HRS, String PERM_NAME)
        {
            DataTable OutTable = new DataTable("Permissions");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Permissions", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@PERM_ID", SqlDbType.BigInt).Value = PERM_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;
                    Command.Parameters.Add("@UPL", SqlDbType.Bit).Value = UPL;
                    Command.Parameters.Add("@USR", SqlDbType.Bit).Value = USR;
                    Command.Parameters.Add("@PAG", SqlDbType.Bit).Value = PAG;
                    Command.Parameters.Add("@HRS", SqlDbType.Bit).Value = HRS;
                    Command.Parameters.Add("@PERM_NAME", SqlDbType.VarChar).Value = PERM_NAME;

                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                }
            }

            return OutTable;
        }

        public static DataTable VW_Hours(Int64? ADM_ID, Int64? HRS_ID, Int64? USR_ID, string HRS_COMPANYNAME, DateTime? HRS_DATE, string HRS_WORKDAY, DateTime? HRS_PAYDAY, Int64? HRS_HOURS, String HRS_COMMENTS)
        {
            DataTable OutTable = new DataTable("Hours");

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_VW_Hours", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@HRS_ID", SqlDbType.BigInt).Value = HRS_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;
                    Command.Parameters.Add("@HRS_COMPANYNAME", SqlDbType.VarChar).Value = HRS_COMPANYNAME;
                    Command.Parameters.Add("@HRS_DATE", SqlDbType.VarChar).Value = HRS_DATE;
                    Command.Parameters.Add("@HRS_WORKDAY", SqlDbType.VarChar).Value = HRS_WORKDAY;
                    Command.Parameters.Add("@HRS_PAYDAY", SqlDbType.DateTime).Value = HRS_PAYDAY;
                    Command.Parameters.Add("@HRS_HOURS", SqlDbType.BigInt).Value = HRS_HOURS;
                    Command.Parameters.Add("@HRS_COMMENTS", SqlDbType.VarChar).Value = HRS_COMMENTS;

                    SqlDataAdapter Adapter = new SqlDataAdapter();
                    Adapter.SelectCommand = Command;
                    Adapter.Fill(OutTable);
                }
            }

            return OutTable;
        }

        public static StoredProcedureValues SP_Hours(int Action, Int64? ADM_ID, Int64? HRS_ID, Int64? USR_ID, string HRS_COMPANYNAME, DateTime? HRS_DATE, string HRS_WORKDAY, DateTime? HRS_PAYDAY, Int64? HRS_HOURS, String HRS_COMMENTS)
        {
            StoredProcedureValues OutValues = new StoredProcedureValues();

            using (SqlConnection Connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Main"].ToString()))
            {
                using (SqlCommand Command = new SqlCommand("SP_Hours", Connection))
                {
                    Command.CommandType = CommandType.StoredProcedure;

                    Command.Parameters.Add("@CMD", SqlDbType.Int).Value = Action;
                    Command.Parameters.Add("@ADM_ID", SqlDbType.BigInt).Value = ADM_ID;
                    Command.Parameters.Add("@HRS_ID", SqlDbType.BigInt).Value = HRS_ID;
                    Command.Parameters.Add("@USR_ID", SqlDbType.BigInt).Value = USR_ID;
                    Command.Parameters.Add("@HRS_COMPANYNAME", SqlDbType.VarChar).Value = HRS_COMPANYNAME;
                    Command.Parameters.Add("@HRS_DATE", SqlDbType.DateTime).Value = HRS_DATE;
                    Command.Parameters.Add("@HRS_WORKDAY", SqlDbType.VarChar).Value = HRS_WORKDAY;
                    Command.Parameters.Add("@HRS_PAYDAY", SqlDbType.DateTime).Value = HRS_PAYDAY;
                    Command.Parameters.Add("@HRS_HOURS", SqlDbType.BigInt).Value = HRS_HOURS;
                    Command.Parameters.Add("@HRS_COMMENTS", SqlDbType.VarChar).Value = HRS_COMMENTS;

                    SqlParameter OutError = Command.Parameters.Add("@OUT_ERROR", SqlDbType.Int);
                    OutError.Direction = ParameterDirection.Output;
                    SqlParameter OutIdentity = Command.Parameters.Add("@OUT_IDENTITY", SqlDbType.Int);
                    OutIdentity.Direction = ParameterDirection.Output;
                    SqlParameter OutMessage = Command.Parameters.Add("@OUT_MESSAGE", SqlDbType.NVarChar, 250);
                    OutMessage.Direction = ParameterDirection.Output;

                    Connection.Open();
                    Command.ExecuteNonQuery();
                    Connection.Close();

                    OutValues.Error = (Int32)OutError.Value;
                    OutValues.Identity = (Int32)OutIdentity.Value;
                    OutValues.Message = OutMessage.Value.ToString();
                }
            }

            return OutValues;
        }

    }
}
